﻿using System;
using System.IO;
using System.Reflection;
using Beaker;
using Beaker.Specs;

namespace OpenCube.IO.Specs.Builders
{
	[CLSCompliant(false)]
	public sealed class ResourceStreamBuilder
		: Builder<Stream>
	{
		private Maybe<Assembly> _assembly;
		private Maybe<string> _prefix;
		private Maybe<string> _fileName;

		public ResourceStreamBuilder InAssembly(Assembly assembly)
		{
			_assembly = assembly;
			return this;
		}

		public ResourceStreamBuilder InFolder(string folderName)
		{
			_prefix = _prefix.HasValue ? _prefix.Value + "." + folderName : folderName;
			return this;
		}

		public ResourceStreamBuilder NearType(Type type)
		{
			_assembly = type.Assembly;
			_prefix = type.Namespace;
			return this;
		}

		public ResourceStreamBuilder WithFilename(string fileName)
		{
			_fileName = fileName;
			return this;
		}

		public override Stream Build()
		{
			Assembly assembly = _assembly.GetValueOrDefault(GetType().Assembly);
			string prefix = _prefix.GetValueOrDefault(GetType().Namespace);
			string fileName = _fileName.GetValueOrDefault("Resource.txt");

			return assembly.GetManifestResourceStream(prefix + "." + fileName);
		}
	}
}
